package com.jlkf.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.jlkf.common.redis.service.JedisClient;
import com.jlkf.dao.CarCaculationMapper;
import com.jlkf.dao.CityRecordMapper;
import com.jlkf.dao.ConfigManagerMapper;
import com.jlkf.dao.DriverAccessoryMapper;
import com.jlkf.dao.DriverMonthlyIncomeMapper;
import com.jlkf.dao.DriverStartServerMapper;
import com.jlkf.dao.DriverTurnoverMapper;
import com.jlkf.dao.DriverWeekIncomeMapper;
import com.jlkf.dao.NoSuccessfulRecordIsDirectCreditsMapper;
import com.jlkf.dao.OrderChargeDetailMapper;
import com.jlkf.dao.OrderItemsMapper;
import com.jlkf.dao.PinpayRecordMapper;
import com.jlkf.dao.PlayTheRewardRewardMapper;
import com.jlkf.dao.StarRemarkMapper;
import com.jlkf.dao.UserBrankMapper;
import com.jlkf.dao.UserConfirmTheOrderingMapper;
import com.jlkf.dao.UserMapper;
import com.jlkf.dao.UserMessageMapper;
import com.jlkf.pojo.CarCaculation;
import com.jlkf.pojo.CityRecord;
import com.jlkf.pojo.ConfigManager;
import com.jlkf.pojo.DriverTurnover;
import com.jlkf.pojo.DriverWeekIncome;
import com.jlkf.pojo.OrderItems;
import com.jlkf.pojo.PinpayRecord;
import com.jlkf.pojo.User;
import com.jlkf.pojo.UserBrank;
import com.jlkf.pojo.UserConfirmTheOrdering;
import com.jlkf.service.util.DateUtil;
import com.jlkf.service.util.FireBaseUtil;
import com.jlkf.service.util.RegexUtil;
import com.jlkf.service.util.SendPushNotification;
import com.jlkf.service.util.StringTools;
import com.jlkf.view.OAMonthlyIncomeOfDrivers;

import io.practiceinsight.pinpayments.pojo.Blance;
import io.practiceinsight.pinpayments.pojo.ErrorMessage;
import io.practiceinsight.pinpayments.pojo.ErrorResponse400;
import io.practiceinsight.pinpayments.pojo.ErrorResponseCard;
import io.practiceinsight.pinpayments.pojo.ResponseBalance;
import io.practiceinsight.pinpayments.pojo.ResponseBalanceEntity;
import io.practiceinsight.pinpayments.pojo.ResponseCharges;
import io.practiceinsight.pinpayments.pojo.ResponseTransfers;
import io.practiceinsight.pinpayments.utils.PinPayHttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class Task {

	//评分 星级
	@Autowired
	private StarRemarkMapper starRemarkMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ConfigManagerMapper configManagerMapper;
	@Autowired
	private DriverStartServerMapper driverStartServerMapper;
	@Autowired
	private OrderItemsMapper orderItemsMapper;
	@Autowired
	private DriverAccessoryMapper driverAccessoryMapper;
	@Autowired
	private OrderChargeDetailMapper orderChargeDetailMapper;
	@Autowired
	private CarCaculationMapper carCaculationMapper;
	@Autowired
	private DriverWeekIncomeMapper driverWeekIncomeMapper;
	@Autowired
	private UserMessageMapper userMessageMapper;
	@Autowired
	private UserConfirmTheOrderingMapper userConfirmTheOrderingMapper;
	@Autowired
	private UserBrankMapper userBrankMapper;
	@Autowired
	private DriverTurnoverMapper driverTurnoverMapper;
	@Autowired
	private PlayTheRewardRewardMapper playTheRewardRewardMapper;
	@Autowired
	private CityRecordMapper cityRecordMapper;
	@Autowired
	private PinpayRecordMapper pinpayRecordMapper;
	@Autowired
	private JedisPool jedisPool; 
	
	    @Scheduled(cron="0 0 1 ? * MON") //每月最后一日的上午1点触发
	    public void StarRemarkTask(){  
	    	Map<String,Object> map = new HashMap<>();
	    	List<User> userList=userMapper.getLogin(map);
	    	for(User u:userList){
	    		map.put("byEvaluation", u.getId());
	    		String s=starRemarkMapper.getUserStarRemarkAVG(map);//用户的评分
	    		System.out.println(s);
	    		if(!StringTools.isEmpty(s)){
	    			u.setRemark(Double.parseDouble(s));//
	    			userMapper.updateByPrimaryKeySelective(u);//更新用户评分
	    		}
	    	}
	     }
	    
	   /* @Scheduled(cron="0 0/1 * * * ?") //每分钟循环  司机端   司机到达乘客上车地点   等待超过XX分钟订单自动取消并收取服务费
	    public void TimeToCancel(){  
	    	Map<String,Object> map = new HashMap<>(); int moreThan=0;
//	    	String ss=jedisClient.get("moreThan");
	    	Jedis jedis = null;
    		if(jedis==null){
				jedis =jedisPool.getResource();
			}
    		String ss=jedis.get("moreThan");
	    	if(StringTools.isEmpty(ss)){
	    		List<ConfigManager> list=configManagerMapper.getList();//默认都会有一条数据
		    	if(list.size()>0){
		    		moreThan=list.get(0).getMoreThan();
		    		jedis.set("moreThan", moreThan+"");
		    	}
	    	}
	    	moreThan=Integer.parseInt(ss);
	    	List<ConfigManager> list=configManagerMapper.getList();//默认都会有一条数据
	    	if(list.size()>0){
	    		moreThan=list.get(0).getMoreThan();
	    	}
	    	List<CarCaculation> carclist=carCaculationMapper.getCarCaculation(map);
	    	List<CarCaculation> ccmlist1 =new ArrayList<>();
	    	 List<DriverStartServer> list1=driverStartServerMapper.getList();
	    	 Date d = new Date();
	    	 for(DriverStartServer dss:list1){
	    		long times= (long) (d.getTime()-dss.getCreateTime().getTime());//分钟
	    		int nu=(int) (times/(1000*60));//司机开始服务
	    		int timesLength=nu-moreThan;
	    		Long orderId=dss.getOrderId();
		    	//  取消  直接扣取客户下单时冻结的
		    	OrderItems oi=orderItemsMapper.selectByPrimaryKey(orderId);
		    	User u = userMapper.selectByPrimaryKey(oi.getuId());
		    	User u1 = userMapper.selectByPrimaryKey(oi.getDirberId());
	    		if(timesLength>=0){//司机等待时间超过配置的时间
	    		//////更新车的状态为空闲
	    		Long carId=oi.getCarId();
	    		DriverAccessory da = new DriverAccessory();
	    		da.setId(carId);
	    		da.setServerStatus(0);//车的状态 服务状态 0空闲 1服务中
	    		int n=driverAccessoryMapper.updateByPrimaryKeySelective(da);//更新车的状态为可接单
	    		String carcresult=jedis.get("carCaculation_carType"+oi.getCarType());
	    		CarCaculation carc=null;
				if(StringTools.isEmpty(carcresult)){
					map.put("carType", oi.getCarType());
					ccmlist1 = carCaculationMapper.getCarCaculation(map);// 计价规则
					JSONArray ja = JSONArray.fromObject(ccmlist1);
					String jlist=ja.toString();
					jedis.set("carCaculation_carType"+oi.getCarType(), jlist);
					if(ccmlist1.size()>0){
						carc=ccmlist1.get(0);
					}
				}else{
					ccmlist1 = JSONArray.toList(JSONArray.fromObject(carcresult),CarCaculation.class);
					if(ccmlist1.size()>0){
						carc=ccmlist1.get(0);
					}
				}
	    		CarCaculation carc=null;
	    		for(CarCaculation carc1:carclist){
	    			if(oi.getCarType()==carc1.getCarType()){
	    				carc=carc1;
	    			}
	    		}
	    			 if(carc!=null&&oi.getCarType()==carc.getCarType()){//用车类型一致 收取取消的服务费
	    				 String fatzebraId = oi.getFatzebraId();// 通过这个id去支付 支付完成之后 修改订单状态 与司机状态
	    				 //去支付 取消的费用
	    				 
	    				 BigDecimal cancel =new BigDecimal(carc.getCancelationFee());
	    		    		oi.setTotalPrice(cancel);//收取取消服务费
	    		    			oi.setStatus(12);//取消
	    		    			orderItemsMapper.updateByPrimaryKeySelective(oi);//更新订单
	    		    			UserMessage um = new UserMessage();// 记录消息
	    						um.setCreateTime(new Date());
	    						um.setmContext("司机在上车地点等你超过10分钟，订单已自动取消，并收取服务费"+cancel+"！");
	    						um.setmName("司机在上车地点等你超过10分钟，订单已自动取消，并收取服务费"+cancel+"！");
	    						um.setmSummary("司机在上车地点等你超过10分钟，订单已自动取消，并收取服务费"+cancel+"！");
	    						um.setName(oi.getName());
	    						um.setType(2);// 1用户端 2司机端
	    						um.setuId(oi.getDirberId());
	    						int n1 = userMessageMapper.insertSelective(um);// 添加
	    						driverStartServerMapper.deleteByPrimaryKey(dss.getId());//删除这个临时记录中的数据
	    						AuroraPush.pushTargetForDriver(u1.getUseEquipment(),"{\"orderId\":" + oi.getId() + ",\"type\":1,\"status\":"+12+"}", u1.getAuroraAlias());
	    						AuroraPush.pushTargetAlertForDriver(u1.getUseEquipment(), "司机超过"+moreThan+"分钟未确认订单为开始服务，系统已自动取消");
	    						AuroraPush.pushTargetForUser(u.getUseEquipment(),"{\"orderId\":" + oi.getId() + ",\"type\":1,\"status\":"+12+"}", u.getAuroraAlias());
	    						AuroraPush.pushTargetAlertForUser(u.getUseEquipment(), "你超过"+moreThan+"分钟未到达约定地点，系统已自动取消", u.getAuroraAlias());
	    			 }
	    		}else if(timesLength==5){//
	    			AuroraPush.pushTargetForUser(u.getUseEquipment(),"{\"orderId\":" + oi.getId() + ",\"type\":1,\"status\":"+oi.getStatus()+"}", u.getAuroraAlias());
					AuroraPush.pushTargetAlertForUser(u.getUseEquipment(), "车辆已等候5分钟，车辆最多等候您10分钟，尽快与司机联系", u.getAuroraAlias());
	    			
	    		}
	    	 }
	    	if(jedis!=null){
				 jedis.close();
			 }
	     } */
	    //区别  1用户端 用户确认订车  司机为空闲状态没有接单 15分钟内不能接单  2.司机取消超过多少次被惩罚
	    @Scheduled(cron="0 0/1 * * * ?") //每分钟循环 用户端 司机若为及时接用户的单 会受到惩罚  订单十五分钟冻结
	    public void UserConfirmTheOrdering(){  
	    	Map<String,Object> map = new HashMap<>();
	    	map.put("difference", 1);//区别  1用户端 用户确认订车  司机为空闲状态没有接单 15分钟内不能接单  2.司机取消超过多少次被惩罚
	    	List<UserConfirmTheOrdering> list=userConfirmTheOrderingMapper.getUserConfirmTheOrdering(map);
	    	Date d = new Date();
//	    	List<ConfigManager> list1=configManagerMapper.getList();//默认都会有一条数据
	    	Jedis jedis = null;
			if(jedis==null){
				jedis =jedisPool.getResource();
			}
	    	int orderTime=0;int bantime=0;//司机当天取消超过多少次会被禁止工作多少分钟
	    	String driverCancelsSendContent="";
	    	 ConfigManager cm=null;
	   			try {
	   				String configManager=jedis.get("configManager");
		   			if(StringTools.isEmpty(configManager)){
		   				 cm = configManagerMapper.selectByPrimaryKey(1);
		   					JSONObject jo = JSONObject.fromObject(cm);
		   					jedis.set("configManager", jo.toString());
		   					orderTime=cm.getOrderTime();
		   					bantime = cm.getBantime();
		   					driverCancelsSendContent=cm.getDriverCancelsSendContent();
		   			}else{
		   				JSONObject jo = JSONObject.fromObject(configManager);
		   				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
		   				orderTime=cm.getOrderTime();
	   					bantime = cm.getBantime();
	   					driverCancelsSendContent=cm.getDriverCancelsSendContent();
		   			}
		    	for(UserConfirmTheOrdering ucto:list){
		    		long times= (long) (d.getTime()-ucto.getCreateTime().getTime());//毫秒
		    		int nu=(int) (times/(1000));//  秒
		    		int timesLength=(int) (nu-orderTime);
		    		if(ucto.getDifference()==1){//  1用户端 用户确认订车  司机为空闲状态没有接单 15分钟内不能接单  2.司机取消超过多少次被惩罚
		    			if(ucto.getType()==1){//当前时间-该记录的时间  得到司机还未接单的时间  如果时间》接单时间 则给前端推送消息  此时司机也不能出现在用户端的司机列表中
				    		if(timesLength>0){//惩罚司机规定时间内没有接单
				    			ucto.setType(2);
				    			userConfirmTheOrderingMapper.updateByPrimaryKeySelective(ucto);
				    			User u = userMapper.selectByPrimaryKey(ucto.getDriverId());
				    			u.setNotOrder(2);//司机这时  不能接单  
				    			userMapper.updateByPrimaryKeySelective(u);//更新司机这是不能出现在乘客的司机列表中
				    			long timess=ucto.getCreateTime().getTime();
				    			FireBaseUtil.postDataForFireBaseDataBase(ucto.getDriverId()+"",  "{\"type\":3,\"status\":1,\"orderId\":0,\"time\":"+timess+"}");
				    		}
			    		}else{//正则惩罚中
			    		//	if(timesLength>=(15*60)){//惩罚时间大于等于15分钟
			    			if(timesLength>=0){
			    				User u = userMapper.selectByPrimaryKey(ucto.getDriverId());
				    			u.setNotOrder(1);//司机这时  可以接单  
				    			userMapper.updateByPrimaryKeySelective(u);//更新司机这是不能出现在乘客的司机列表中
				    			userConfirmTheOrderingMapper.deleteByPrimaryKey(ucto.getId());
				    			FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"type\":3,\"orderId\":0,\"status\":2}");
			    			}
		    		}
		    		}else{
		    			if(ucto.getType()==1){//当前时间-该记录的时间  得到司机还未接单的时间  如果时间》接单时间 则给前端推送消息  此时司机也不能出现在用户端的司机列表中
				    		if(timesLength>=0){//惩罚司机规定时间内没有接单
				    			ucto.setType(2);
				    			userConfirmTheOrderingMapper.updateByPrimaryKeySelective(ucto);
				    			User u = userMapper.selectByPrimaryKey(ucto.getDriverId());
				    			u.setNotOrder(4);//司机这时  不能接单  
				    			userMapper.updateByPrimaryKeySelective(u);//更新司机这是不能出现在乘客的司机列表中
				    			FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"type\":8,\"status\":1,\"orderId\":0,\"time\":"+ucto.getCreateTime()+",\"time_length\":"+bantime+"}");
				    			FireBaseUtil.sendMessageAlert(u.getUseEquipment(), driverCancelsSendContent);
				    		}
			    		}else{//正则惩罚中
			    			if(timesLength>=(bantime*60)){//惩罚时间大于等于15分钟
			    				User u = userMapper.selectByPrimaryKey(ucto.getDriverId());
				    			u.setNotOrder(1);//司机这时  可以接单  
				    			userMapper.updateByPrimaryKeySelective(u);//更新司机这是不能出现在乘客的司机列表中
				    			userConfirmTheOrderingMapper.deleteByPrimaryKey(ucto.getId());
				    			FireBaseUtil.sendMessageAlert(u.getUseEquipment(), driverCancelsSendContent);
				    			FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"type\":8,\"orderId\":0,\"status\":2}");
			    			}
		    		}
		    	}
		    		
		    		}
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					if(jedis!=null){
						jedis.close();
					}
				}
	     }
	    
	    @Scheduled(cron="0 0 1 1 * ?") //每个月第一天执行   司机月收入报表  每月1号1点执行任务
//	    @Scheduled(cron="0 0/1 * * * ?")
	    public void monthlyIncomeOfDrivers(){  
	    	Map<String,Object> map = new HashMap<>();
	    	map.put("identity", 2);//身份是司机的用户
	    	 List<User>  userlist=userMapper.getLogin(map);
	    	 Date d = new Date();
	    	 Calendar calendar = Calendar.getInstance();//日历对象  
	         calendar.setTime(d);//设置当前日期  
	         calendar.add(Calendar.MONTH, -1);//月份减一  
	         java.util.Date date =calendar.getTime();
	    	String ym= DateUtil.format(date, "yyyy-MM");
	    	map.put("date", ym);//上个月的时间
	    	List<CarCaculation> carclist=  carCaculationMapper.getCarCaculation(map);//规则
	    	 for(User user:userlist){
	    		 Double totalTurnover1= 0.0;Double platformFor1 =0.0; Double driverIncome1 =0.0;
	    		 Double roadPrice1=0.0;Double tip1 = 0.0;Double cleanness1=0.0;Double time=0.0;
	    		 map.put("driverId", user.getId());
	    		 map.put("status", 1);//月
	    		 //当月营业总额 司机确认账单时发生的金额 包含未抵扣优惠的金额   司机结算金额  平台扣取平台费之后的金额
	    		 //司机结算=当月营业额-（当月营业额*平台收取的费用）
	    			 OAMonthlyIncomeOfDrivers oamid= orderChargeDetailMapper.monthlyStatistics(map);//查询出上月的司机月收入
	    			 if(oamid!=null){
	    				 totalTurnover1= oamid.getTotalTurnover()==null?0:oamid.getTotalTurnover();//总的营业额
						   platformFor1 = oamid.getFab()==null?0:oamid.getFab();//平台收取
						  driverIncome1  =oamid.getDriverIncome()==null?0:oamid.getDriverIncome();//司机收入
						  roadPrice1=oamid.getTolls()==null?0:oamid.getTolls();//过路费
						  tip1 = oamid.getTip()==null?0:oamid.getTip();//小费
						  cleanness1 = oamid.getCleanness()==null?0:oamid.getCleanness();//清洁费
						  time=oamid.getTime()==null?0.0:oamid.getTime();
	    			 }
	    			Integer orderNum= orderItemsMapper.getDriverOrderCount(map);
	    	         saveDriverTurnover(cleanness1, user.getId(), user.getFirstName(), roadPrice1, tip1, totalTurnover1, platformFor1, user.getTelephone(), orderNum,time);//保存司机月结算信息
	    	 }
	     } 
	    
	    private void saveDriverTurnover(Double cleanness1,Long driverId,String firstName,Double roadPrice1,Double tip1,Double totalTurnover1,Double platformFor1,String telephone,Integer orderNum,Double time){
	    	 Calendar cal = Calendar.getInstance();  
	         cal.setTime(new Date());  
	         cal.add(Calendar.MONTH, -1);
	         System.out.println(cal.getTime());
	    	 DriverTurnover record = new DriverTurnover();
    		 record.setCleanness(cleanness1);
    		 record.setCreateTime(new Date());
    		 record.setDriverId(driverId);
    		 record.setDriverName(firstName);
    		 record.setMonth(cal.getTime());//记录的该月份为上个月的
    		 record.setStatus(3);
    		 record.setRoadPrice(roadPrice1);
    		 record.setTip(tip1);
    		 record.setTurnover(totalTurnover1);
    		 record.setSettlementTime(new Date());
    		 record.setMonthlyPlatformCollection(platformFor1);
    		 record.setDriverPhone(telephone);
    		 record.setOrderNum(orderNum);
    		 record.setTotalServiceTime(time);
    		int num= driverTurnoverMapper.insertSelective(record);//保存该司机这个月的收入账单
	    }
	    
//	    @Scheduled(cron="0 0 1 * * ?") //每个星期执行   司机月收入报表  每天一点执行任务 划款
	    @Scheduled(cron="0 0 1 * * ?") 
//	    @Scheduled(cron="0 0/1 * * * ?")
	    public void weeklyIncomeOfDrivers(){  
	    	Map<String,Object> map = new HashMap<>();
	    	map.put("identity", 2);//身份是司机的用户
	    	 List<User>  userlist=userMapper.getLogin(map);
	    	 Date d = new Date();
	    	 Calendar calendar = Calendar.getInstance();//日历对象  
	         calendar.setTime(d);//设置当前日期  
	         int day = calendar.get(Calendar.DAY_OF_WEEK);//今天 是 一周中的那一天
	         int dayOfWeek=1;
	         StringBuffer sb = new StringBuffer();
//	         List<ConfigManager> cmlist= configManagerMapper.getList();//获取一周中那一天执行司机结算
	         ConfigManager cm=null;
	         Jedis jedis = null;
	         Date d1=null;
 			if(jedis==null){
 				jedis =jedisPool.getResource();
 			}
				try {
					String configManager=jedis.get("configManager");
					if(StringTools.isEmpty(configManager)){
						 cm = configManagerMapper.selectByPrimaryKey(1);
							JSONObject jo = JSONObject.fromObject(cm);
							jedis.set("configManager", jo.toString());
							dayOfWeek = cm.getWeeklySettlementSetting();
					}else{
						JSONObject jo = JSONObject.fromObject(configManager);
						cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
						dayOfWeek = cm.getWeeklySettlementSetting();
					}
		          if(dayOfWeek==day){//今日时间正好是系统配置的时间 执行司机结算
		        	  List<CarCaculation> carclist=  carCaculationMapper.getCarCaculation(map);//规则
		 	    	 for(User user:userlist){
		 	    		Map<String,Object> map1 = new HashMap<>();
		 	    		 Double totalTurnover1= 0.0;Double platformFor1 =0.0; Double driverIncome1 =0.0;
		 	    		 Double roadPrice1=0.0;Double tip1 = 0.0;Double cleanness1=0.0;Double time=0.0;
		 	    		 map1.put("driverId", user.getId());
		 	    		 System.out.println("driverId="+user.getId());
		 	    		 //当月营业总额 司机确认账单时发生的金额 包含未抵扣优惠的金额   司机结算金额  平台扣取平台费之后的金额
		 	    		 //司机结算=当月营业额-（当月营业额*平台收取的费用）
//		 	    			 map1.put("carType", i);
		 	    			 map1.put("startTime",DateUtil.format( geLastWeekMonday(d), "yyyy-MM-dd"));//结算时间开始时间
		 	    			 map1.put("endTime",DateUtil.format(  geLendWeekMonday(geLastWeekMonday(d)), "yyyy-MM-dd"));//结算时间 结束时间
		 	    			d1=geLendWeekMonday(geLastWeekMonday(d));
		 	    			 OAMonthlyIncomeOfDrivers oamid= orderChargeDetailMapper.monthlyStatistics(map1);//查询出上月的司机月收入
		 	    			 List<Long> longlist=orderChargeDetailMapper.monthlyStatisticsOrderId(map1);//订单
		 	    			 if(oamid!=null){ 
	    						  totalTurnover1= oamid.getTotalTurnover()==null?0:oamid.getTotalTurnover();//总的营业额
	    						  platformFor1 = oamid.getFab()==null?0:oamid.getFab();//平台收取
	    						  driverIncome1  =oamid.getDriverIncome()==null?0:oamid.getDriverIncome();//司机收入
	    						  roadPrice1=oamid.getTolls()==null?0:oamid.getTolls();//过路费
	    						  tip1 = oamid.getTip()==null?0:oamid.getTip();//小费
	    						  cleanness1 = oamid.getCleanness()==null?0:oamid.getCleanness();//清洁费
	    						  time = oamid.getTime()==null?0.0:oamid.getTime();
//		 	    			 }
		 	    			 map1.remove("carType");
		 	    		 }
		 	    		 /////////////////////司机给平台划账///////////////////////////////////
		 	    		 //司机个人所得
//		 	    		Double personalIncome=totalTurnover1-platformFor1;
		 	    		Integer personalIncome1 = (int) (driverIncome1*100);
		 	    		List<UserBrank> ublist = userBrankMapper.getUserCards(user.getId());//查询用户银行卡
		 	    		 if(ublist.size()>0&&driverIncome1>0){//司机只会有一张银行卡司机能拿到的金额
		 	    			UserBrank ub = ublist.get(0);
		 	    			String result ="";
		 	    			String jrc =null;
		 	    			 Map<String,String> sendBalanceMap=new HashMap<>();
			 	    			Map<String,Object> ResponseBalanceMap=	PinPayHttpUtils.getBalance(sendBalanceMap);	 
			 	    			 if(ResponseBalanceMap!=null&&(int)ResponseBalanceMap.get("code")==200){//查询成功
			 	    				String rb= (String)ResponseBalanceMap.get("obj");
			 	    				ResponseBalance rb1=StringTools.json2Obj(rb, ResponseBalance.class);
			 	    				Integer amount=rb1.getResponse().getAvailable().get(0).getAmount();
			 	    				 map1.remove("type");
	    							 map1.put("type", 2);
	    							Double platform_reward=playTheRewardRewardMapper.getSum(map1);//平台奖励 邀请等会赠送*/	
			 	    				if(amount!=null&&amount>personalIncome1){//比较 如果可用余额大于转账给司机的金额 就转账  不够就不转
			 	    						System.out.println("司机划款 result=" + result);
			 	    						Map<String, String> sendMap=new HashMap<>();
			 	    				    	sendMap.put("amount", personalIncome1+"");//需要支付的金额
			 	    				    	sendMap.put("currency", "AUD");
			 	    				    	sendMap.put("description", "Earnings for this week");
			 	    				    	sendMap.put("recipient", ub.getAvoidCloseToPayToken());//收件人凭证
			 	    				    	Map<String,Object> resut=	PinPayHttpUtils.sendPinPayCreateTransfersPost(sendMap);
			 	    				    	 if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
			 	    				    		 ResponseTransfers rc=(ResponseTransfers) resut.get("obj");
			 	    				    		   jrc = JSONObject.fromObject(rc).toString();
			 	    								 insertDriverWeekIncome(1, cleanness1, driverIncome1, user, platformFor1, roadPrice1, tip1, totalTurnover1, platform_reward, longlist.size(), time, d1);//已扣钱
			 	    					    		if(longlist.size()>0){
			 	    					    			for(Long ll:longlist){
			 	    					    				OrderItems records= new OrderItems();
			 	    					    				records.setId(ll);
			 	    					    				records.setStatus(13);
			 	    					    				int nu=orderItemsMapper.updateByPrimaryKeySelective(records);
			 	    					    			}
			 	    					    		}
			 	    				   		}else {
			 	    				   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
			 	    				   			jrc = JSONObject.fromObject(rc).toString();
			 	    				   			if(totalTurnover1!=0||platformFor1!=0||driverIncome1!=0||roadPrice1!=0|| cleanness1!=0|| tip1!=0||cleanness1!=0||time!=0){
//			 	    				   			 map1.remove("type");
//			 	    							 map1.put("type", 2);
//			 	    							 Double platform_reward=playTheRewardRewardMapper.getSum(map1);//平台奖励 邀请等会赠送*/	
			 	    							 insertDriverWeekIncome(2, cleanness1, driverIncome1, user, platformFor1, roadPrice1, tip1, totalTurnover1, platform_reward, longlist.size(), time, d1);
			 	    				   			}
			 	    						}
			 	    				    	  map1.remove("driverId");
			 	    				    	  PinpayRecord ppr = new PinpayRecord(null,jrc,(int)resut.get("code"),new Date(),2);//支付记录
			 	    			    		  pinpayRecordMapper.insertSelective(ppr);
			 	    			                /////////////////////司机给平台划账/////////////////////////////////// 
			 	    				}else{
			 	    					 insertDriverWeekIncome(2, cleanness1, driverIncome1, user, platformFor1, roadPrice1, tip1, totalTurnover1, platform_reward, longlist.size(), time, d);
			 	    				}
			 	    				  PinpayRecord ppr = new PinpayRecord(null,jrc,(int)ResponseBalanceMap.get("code"),new Date(),5);//支付记录
	 	    			    		  pinpayRecordMapper.insertSelective(ppr);
			 	    			 }
		 	    	 }
		          }
		 	    	 }
				} catch (Exception e) {
					e.printStackTrace();
					if(jedis==null){
		 				jedis.close();;
		 			}
				}finally {
					if(jedis!=null){
						jedis.close();
					}
				}
	     }
	    
	    private void insertDriverWeekIncome(Integer type,Double cleanness1,Double driverIncome1,User user,Double platformFor1,Double roadPrice1,Double tip1,Double totalTurnover1,Double platform_reward,Integer longList,Double  time,Date d){
	    	 DriverWeekIncome record = new DriverWeekIncome();//周结算 记录
			 record.setCleanness(cleanness1);
	   		 record.setCreateTime(new Date());
	   		 record.setDriverAndSettlement(driverIncome1);
	   		 record.setDriverId(user.getId());
	   		 record.setDriverName(user.getFirstName());
	   		 record.setDriverPhone(user.getTelephone());
	   		 record.setMonth(d);
	   		 record.setMonthlyPlatformCollection(platformFor1);
	   		 record.setRoadPrice(roadPrice1);
	   		 record.setTip(tip1);
	   		 record.setTurnover(totalTurnover1);
	   		 record.setPlatformReward(platform_reward);
	   		 record.setOrderNum(longList);
	   		 record.setTotalServiceTime(time);
	   		 record.setType(type);//1已扣款 2未扣款
	   		 int n=driverWeekIncomeMapper.insertSelective(record);//保存该司机这周的收入账单
	    }
	    
	    
	    //获取上周周一
	    public static Date geLastWeekMonday(Date date) {  
            Calendar cal = Calendar.getInstance();  
            cal.setTime(getThisWeekMonday(date));  
            cal.add(Calendar.DATE, -7);  
            return cal.getTime();  
        } 
	    //给定时间  本周结束时间
	    public static Date geLendWeekMonday(Date date) {  
            Calendar cal = Calendar.getInstance();  
            cal.setTime(date);  
            cal.add(Calendar.DATE, 7);  
            return cal.getTime();  
        } 
	    public static Date getThisWeekMonday(Date date) {  
	        Calendar cal = Calendar.getInstance();  
	        cal.setTime(date);  
	        // 获得当前日期是一个星期的第几天  
	        int day = cal.get(Calendar.DAY_OF_WEEK);  
	        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值  
	        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);  
	        return cal.getTime();  
	    }  
	 
	    
	    
	    @Scheduled(cron="0 0/30 * * * ?") //每个城市的司机在线时长  工作时长设置 到了时间 司机设置为下线
	    public void onlineTime(){  
	    	Map<String,Object> map= new HashMap<>();
	    	map.put("identity", 2);
	    	List<User> driverList = userMapper.getNameAndTel(map);//查询司机信息
	    	Date d = new Date();//当前时间
	    	 List<CityRecord> list=cityRecordMapper.getList(map);//城市列表
	    	 for(CityRecord cr:list){
	    		 for(User u:driverList){
	    				double longTime=0;//单位是小时
	    			 if(!RegexUtil.isNull(u.getCityId())&&cr.getId()==u.getCityId()){//司机绑定了城市，且司机为该城市的司机
	    				if(!RegexUtil.isNull(u.getNotOrder())&&u.getNotOrder()!=3){//该司机工作中
	    					Integer works= cr.getTheServiceTime();//工作的时长 小时
		    				if(u.getLoginTime()!=null){
		    					long longTime1=d.getTime()-u.getLoginTime().getTime();//
		    					 longTime = (double)longTime1/(60*1000)*60;
		    				}
		    				if(longTime>=works){//工作时间大于等于服务时间
		    					u.setNotOrder(3);//疲劳驾驶
		    					u.setIsOnline(2);//状态为下线
		    					u.setExitTime(d);//退出时间为当前时间
		    					userMapper.updateByPrimaryKeySelective(u);
		    					FireBaseUtil.sendMessageAlert(u.getUseEquipment(), "You have reached"+works+"hours today. Please take a rest.");
				    			FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{type:7,\"orderId\":0,status:1}");
		    				}
	    				}else{
	    					if(u.getExitTime()!=null){//退出时间
		    					long longTime1=d.getTime()-u.getExitTime().getTime();//
		    					 longTime = (double)longTime1/(60*1000)*60;
		    				}
	    					if(longTime>=4){//疲劳驾驶被禁用了4个小时
		    					u.setNotOrder(1);//疲劳驾驶
		    					userMapper.updateByPrimaryKeySelective(u);
		    					FireBaseUtil.sendMessageAlert(u.getUseEquipment(), "You can take the order.");
				    			FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{type:7,\"orderId\":0,status:2}");
		    				}
	    				}
	    				
	    			 }
	    		 }
	    	 }
	     } 
	    
	    public static void main(String[] args) {  
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
	        try {  
	            Date date = sdf.parse("2018-02-08");  
	            System.out.println("今天是" + sdf.format(date));  
	            System.out.println("上周一" + sdf.format(geLastWeekMonday(date)));  
	            
	            System.out.println("本周天" + sdf.format(geLendWeekMonday(geLastWeekMonday(date))));  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    } 
}
